<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Admin\Stuff\StuffDeleteAction;
use App\Admin\Grid\NGrid;
use App\Admin\Tools\Stuff\StuffDeleteTool;
use App\Admin\Tools\Stuff\StuffStatusTransTool;
use App\Models\AdminUsersRelatedModel;
use Encore\Admin\Controllers\UserController;
use Encore\Admin\Form;
use Encore\Admin\Grid\Displayers\Actions;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class StuffController extends UserController
{
    public function title(): string
    {
        return '员工管理';
    }

    public function grid(): NGrid
    {
        $grid = new NGrid(new AdminUsersRelatedModel);
        $grid->model()->leftJoin('admin_users', 'admin_users.id', 'user_id')
//            ->where('admin_users_related.main_id', '>', 0)
            ->orderByDesc('admin_users_related.id');
        if (!ISADMIN) {
            if (in_array(Auth::user()->roles->first()->slug, ['boss', 'finance'])) {
                $grid->model()->orWhere('admin_users_related.main_id', MAINID)
                    ->orWhere('admin_users_related.user_id', MAINID);
            } else $grid->model()->where('admin_users_related.user_id', USERID);
        }
//        if (!ISADMIN) {
//            if (in_array(Auth::user()->roles->first()->slug, ['boss', 'finance'])) $grid->model()->where('admin_users_related.main_id', MAINID);
//            else $grid->model()->where('admin_users_related.user_id', USERID);
//        }
        $grid->filter(function ($filter) {
            $filter->disableIdFilter();
            $filter->column(1 / 2, function ($filter) {
                $filter->equal('username', __('stuff.username'))->integer();
                $filter->like('mobile', __('l.mobile'));
            });
            $filter->column(1 / 2, function ($filter) {
                $filter->date('service_date', __('stuff.serviceDate'));
            });
        });
        if(Auth::user()->roles->first()->slug == 'Administrator') $grid->column('user_id', 'ID')->sortable();
        $grid->column('user_id', 'ID')->sortable();
        $grid->column('username', '账号名');
        $grid->column('name', '昵称');
        $grid->column('role', '角色')->display(function () {
            $model = DB::table('admin_roles')
                ->leftJoin('admin_role_users', 'admin_role_users.role_id', '=', 'admin_roles.id')
                ->where('user_id', $this->user_id)
                ->first();
            return is_null($model) ? '' : $model->name;
        });
        $grid->column('avatar', __('stuff.avatar'))->image('/upload', 100, 100);
        $grid->column('qq', __('l.qq'));
        $grid->column('mobile', __('l.mobile'));
        $grid->column('id_number', __('l.idNumber'));
        $grid->column('service_date', __('stuff.serviceDate'));
        $grid->column('living_address', __('stuff.livingAddress'));
        $grid->column('remark', __('l.remark'));
        $grid->column('status', '账号状态')->using(['0' => '禁用', 1 => '启用']);
        $grid->column('last_login_at', '上一次登录时间');
        $grid->actions(function (Actions $action) {
            $action->disableEdit(false);
            $action->disableDelete();
            $action->disableView();

            $action->append(new StuffStatusTransTool($action->row->user_id, $action->row->name, $action->row->username, $action->row->status));
            // $action->append(new StuffDeleteTool($action->row->user_id));

        });
        $grid->disableActions(false);
        return $grid;
    }

    public function form(): Form
    {
        DB::beginTransaction();
        $form = parent::form();
        $form->column(1 / 2, function (Form $form) {
            parent::form();
        });

        $relatedTag = is_numeric(request()->segment(3)) ?? 0;

        if (!$relatedTag) {
            $form->column(1 / 2, function (Form $form) {
                $form->text('admin_users_related.mobile', __('l.mobile'))->attribute('maxlength', 30);
                $form->text('admin_users_related.qq', __('l.qq'));
                $form->text('admin_users_related.id_number', __('l.idNumber'))->attribute('maxlength', 30);
                $form->date('admin_users_related.service_date', __('stuff.serviceDate'))->format('YYYY-MM-DD');
                $form->text('admin_users_related.living_address', '居住地址');
                $form->textarea('admin_users_related.remark', __('l.remark'));
            });
        } else {
            $adminUserRelated = AdminUsersRelatedModel::query()->where('user_id', request()->segment(3))->first();
            $form->column(1 / 2, function (Form $form) use ($adminUserRelated) {
                $form->text('admin_users_related.mobile', __('l.mobile'))->attribute('maxlength', 30)
                    ->default($adminUserRelated->mobile);
                $form->text('admin_users_related.qq', __('l.qq'))->default($adminUserRelated->qq);
                $form->text('admin_users_related.id_number', __('l.idNumber'))->attribute('maxlength', 30)
                    ->default($adminUserRelated->id_number);
                $form->date('admin_users_related.service_date', __('stuff.serviceDate'))
                    ->default($adminUserRelated->service_date)
                    ->format('YYYY-MM-DD');
                $form->text('admin_users_related.home_address', __('stuff.homeAddress'))->default($adminUserRelated->home_address);
                $form->textarea('admin_users_related.remark', __('l.remark'))->default($adminUserRelated->remark);
            });
        }

        $form->saved(function (Form $form) {
            $arr = [
                'mobile' => $form->admin_users_related['mobile'],
                'qq' => $form->admin_users_related['qq'],
                'id_number' => $form->admin_users_related['id_number'],
                'service_date' => $form->admin_users_related['service_date'],
                'living_address' => $form->admin_users_related['living_address'],
                'remark' => $form->admin_users_related['remark'],
            ];

            if ($form->isCreating()) {
                AdminUsersRelatedModel::query()->insert(array_merge($arr, [
                    'main_id' => ISMAIN ? USERID : MAINID,
                    'user_id' => $form->model()->id,
                    'created_at' => Carbon::now(),
                ]));
            }

            if ($form->isEditing()) {
                AdminUsersRelatedModel::query()->where([
                    'user_id' => $form->model()->id,
                ])
                    ->update($arr);
            }
        });
        DB::commit();
        return $form->confirm('确定提交吗?');
    }
}
